package com.utils {
	
	//AIR才有这些类
	import com.Global;
	import com.adobe.images.PNGEncoder;
	import fairygui.utils.GTimers;
	
	import flash.desktop.NativeProcess;
	import flash.desktop.NativeProcessStartupInfo;
	import flash.display.BitmapData;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.FileFilter;
	import flash.system.Capabilities;
	import flash.utils.ByteArray;
	
	/**
	 * 文件类工具 2013-3-29 22:39
	 * @author taojianlong
	 */
	public class FileUtils {
		
		public static const FILE_XML:String = "xml";
		public static const FILE_JPG:String = "jpg";
		public static const FILE_JPEG:String = "jpeg";
		public static const FILE_PNG:String = "png";
		public static const FILE_TXT:String = "txt";
		public static const FILE_MP3:String = "mp3";
		public static const FILE_EXE:String = "exe";
		public static const FILE_SWF:String = "swf";
		public static const FILE_BAT:String = "bat";
		public static const FILE_XLS:String = "xls";
		public static const FILE_JSON:String = "json";
		public static const FILE_BIN:String = "bin";
		
		public static const IMAGES_FILEFILTER:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");
		public static const XML_FILEFILTER:FileFilter = new FileFilter("XML", "*.xml");
		public static const TXT_FILEFILTER:FileFilter = new FileFilter("TXT", "*.txt");
		public static const SWF_FILEFILTER:FileFilter = new FileFilter("SWF", "*.swf");
		public static const MP3_FILEFILTER:FileFilter = new FileFilter("MP3", "*.mp3");
		public static const XLS_FILEFILTER:FileFilter = new FileFilter("XLS", "*.xls");
		public static const GIF_FILEFILTER:FileFilter = new FileFilter("GIF", "*.gif");
		
		/**
		 * 获得文件后缀名
		 * @param url 文件路径
		 * @return <b>String</b> 文件后缀名
		 *
		 */
		public static function getFileExtension(url:String):String {
			//切掉路径后面的参数
			var searchString:String = url.indexOf("?") > -1 ? url.substring(0, url.indexOf("?")) : url;
			
			//截取后缀
			var finalPart:String = searchString.substring(searchString.lastIndexOf("/"));
			return finalPart.substring(finalPart.lastIndexOf(".") + 1).toLowerCase();
		}
		
		/**
		 * 获取文件名
		 * @param	file
		 * @return
		 */
		public static function getFileName( file:File ):String{
			
			
			//切掉路径后面的参数
			var name:String = file.name.indexOf(".") > -1 ? file.name.substring(0, file.name.indexOf(".")) : file.name;			
			return name;
		}
		
		/**
		 * 获取目录文件长度
		 * @param	file	目录
		 * @param	doChild 是否遍历子目录	
		 * @return 
		 */
		public static function getFileLength( file:File , doChild:Boolean = true ):int{
			
			var count:int = 0;
			if ( file ){
				if ( file.isDirectory ){
					var arr:Array = file.getDirectoryListing();
					var f:File = null;
					if ( arr.length > 0 ){
						for each( f in arr){
							if ( f.isDirectory && doChild ){
								count += getFileLength( f , doChild );
							}else{
								count += 1;
							}
						}
					}
				}else{
					count += 1;
				}
			}			
			return count;
		}
		
		/**
		 * 将文件地址保存为指定格式地址,未验证
		 * @param	url    文件地址
		 * @param	format 文件格式
		 */
		public static function toFileName(url:String, format:String = FILE_XML):String {
			
			var ind:int = url.lastIndexOf(".");
			
			return ind != -1 ? url.substr(0, ind + 1) + format : url + "." + format;
		}
		
		/**
		 * 保存文本数据,在AIR项目时打开
		 * @param	url
		 * @param	data
		 * @param	complete
		 * @param   params 完成事件的参数
		 */
		public static function saveUTFFile(url:String, data:String, file:File = null, complete:Function = null, params:Array = null):void {
			
			if (file == null) {
				file = new File(url);
			} else {
				var extension:String = getFileExtension(url);
				file.nativePath = toFileName(file.nativePath, extension);
			}
			var stream:FileStream = new FileStream();
			if (!file.exists) //如果不存在该文件则创建一个新文件并打开
			{
				stream.open(file, FileMode.WRITE);
				stream.writeUTFBytes(data);
				stream.close();
				if (complete != null) {
					complete();
				}
			} else {
				
				try {
					stream.open(file, FileMode.WRITE);
					stream.writeUTFBytes(data);
					stream.close();
					if (complete != null) {
						complete();
					}
				} catch (e:Error) {
					trace("[FileUtils]saveUTFFile=====>error:" + e.message);
				}
			}
		}
		
		/**
		 * 保存图片
		 * @param	bmd
		 * @param	path/ 	目录地址
		 * @param 	name  	文件名字
		 * @param 	format	文件格式
		 */
		public static function saveBitmapData( bmd:BitmapData , path:String , name:String , format:String = ".png" , complete:Function = null ):void{
			
			if ( bmd != null ){
				
				var url:String = path + name + format;
				var bytes:ByteArray = PNGEncoder.encode( bmd );
				
				FileUtils.saveByte( bytes , url , null , complete );
			}
		}
		
		/**
		 * 保存流文件
		 * @param	byte
		 * @param	url
		 * @param	file
		 * @param	complete
		 */
		public static function saveByte(bytes:ByteArray, url:String, file:File = null, complete:Function = null, args:Array = null):void {
			
			if (url == "" && file == null) {
				return;
			}
			
			if (file == null) {
				file = new File(url);
			}
			
			var extension:String = getFileExtension(url);
			file.nativePath = toFileName(file.nativePath, extension);
			var stream:FileStream = new FileStream();
			if (!file.exists) //如果不存在该文件则创建一个新文件并打开
			{
				stream.open(file, FileMode.WRITE);
				stream.writeBytes(bytes || new ByteArray());
				stream.close();
				if (complete != null) {
					complete.apply(null, args);
				}
			} else {
				
				try {
					stream.open(file, FileMode.WRITE);
					stream.writeBytes(bytes || new ByteArray());
					stream.close();
					if (complete != null) {
						complete.apply(null, args);
					}
				} catch (e:Error) {
					trace("[FileUtils] saveByte error:=====>" + e.message);
				}
			}
		}
		
		/**
		 * 遍历所有文件及目录
		 * @param	file	文件目录
		 * @param 	format	要遍历的文件后缀名
		 * @param 	files	当前目录的列表
		 * @param 	func	遍历时触发
		 * @param 	funcParams 遍历方法参数
		 * @param 	list 	所有目录列表
		 */
		public static function loopFiles(file:File, format:String = "asset", func:Function = null, funcParams:Array = null, files:Array = null, list:Array = null):Array {
			
			list = list || [];
			if (file == null) {
				return list;
			}
			format = format.replace( /\.|\*/g , "" );
			var formats:Array = format.split( "," );//clong 2020.5.2
			var params:Array = null;
			if (file.isDirectory) {
				files = files || file.getDirectoryListing();
				while (files && files.length > 0) {
					var f:File = files.shift();
					if (f != null) {
						if (f.isDirectory) { //目录
							//trace( "导入目录: " + f.nativePath );						
							loopFiles(f, format, func, funcParams, null, list);
						} else if (format) {
							if ( formats.indexOf( f.extension ) != -1 ) {//f.name.indexOf(format) != -1
								list.push(f);
							} else {
								continue;
							}
						} else {
							list.push(f);
						}
						
						if (func != null) {
							params = funcParams || [];
							params.unshift(f);
							func.apply(null, params);
						}
					}
				}
			} else if (!format || formats.indexOf( f.extension ) != -1 ) {//file.name.indexOf(format) != -1
				list.push(file);
				if (func != null) {
					params = funcParams || [];
					params.unshift(file);
					func.apply(null, params);
				}
			}
			return list;
		}
		
		/**
		 * 打开本地目录
		 * @param	file
		 */
		public static function openLocalFile(file:File):void {
			
			var isMac:Boolean = Capabilities.os.toLowerCase().indexOf("mac") != -1;//是否为mac系统
			var nps:NativeProcessStartupInfo = new NativeProcessStartupInfo();
			var vec:Vector.<String> = new Vector.<String>;
			if (!isMac) {
				nps.executable = new File("c:\\windows\\explorer.exe");
				vec.push("/select," + file.nativePath);
			} else {
				nps.executable = new File("/usr/bin/open");
				vec.push("-R");
				vec.push(file.nativePath);
			}
			nps.arguments = vec;
			//var _loc_5:* = new NativeProcess();
			try{
				new NativeProcess().start(nps);
			}catch ( e:Error){
				
			}			
		}
		
		
		/**
		 * 复制字符
		 * @param	char
		 * @param	num
		 * @return
		 */
		public static function copyChar(char:String, num:int = 1, join:String = ""):String {

			var arr:Array = [];
			for (var i:int = 0; i < num; i++) {
				arr.push(char);
			}
			return arr.join(join);
		}
		
		/*
		 * GET the current date format like this(2010/07/06  11:37:56  星期二)
		 * GetDateFormat
		 */
		public static function DateToString(date:Date):String {
			var str:String;
			var DAYS:Array = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
			//var date:Date = new Date();
			var dYear:String = String(date.getFullYear());
			var dMouth:String = String((date.getMonth() + 1 < 10) ? "0" : "") + (date.getMonth() + 1);
			var dDate:String = String((date.getDate() < 10) ? "0" : "") + date.getDate();
			var ret:String = "";
			ret += dYear + "/" + dMouth + "/" + dDate + "  "; //年月日    
			ret += ((date.getHours() < 10) ? "0" : "") + date.getHours() + ":";
			ret += ((date.getMinutes() < 10) ? "0" : "") + date.getMinutes() + ":";
			ret += ((date.getSeconds() < 10) ? "0" : "") + date.getSeconds() + "  ";
			ret += DAYS[date.getDay()] + "";
			str = ret;
			return str;
		}
	}
}